﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using GmailMetroNotifier.Client.Common;
using GmailMetroNotifier.Client.Properties;

namespace GmailMetroNotifier.Client.Business
{
    /// <summary>
    /// Provides operations used for retrieving a Gmail account Atom feed.
    /// </summary>
    public class AtomFeedProvider : IAtomFeedProvider
    {
        /// <summary>
        /// Retrieves an Atom feed contents using the given credentials.
        /// </summary>
        /// <param name="credential">The credentials to be used for retrieving the Atom feed.</param>
        /// <returns>The contents of the Atom feed, or null otherwise.</returns>
        /// <exception cref="ArgumentNullException">Thrown when null credential is passed.</exception>
        /// <exception cref="AuthenticationFailedException">Thrown when credentials are not valid.</exception>
        public string GetAtomFeed(NetworkCredential credential)
        {
            if (credential == null)
            {
                throw new ArgumentNullException("credential");
            }

            try
            {
                WebClient client = new WebClient();

                client.Credentials = credential;

                return client.DownloadString(Constants.Urls.GmailAtomFeedUrl);
            }
            catch (WebException exception)
            {
                HttpWebResponse response = (exception.Response as HttpWebResponse);

                if (exception.Status == WebExceptionStatus.ProtocolError
                    && response != null
                    && response.StatusCode == HttpStatusCode.Unauthorized)
                {
                    throw new AuthenticationFailedException(Resources.EXCEPTION_MSG_AUTHENTICATION_FAILED, credential, exception);
                }
                else
                {
                    throw;
                }
            }
        }
    }
}
